import { useUserStore } from '@/store/userStore'

const userStore = useUserStore()

// 配置接口，用于初始化WebSocket
interface WebSocketOptions {
  onMessage?: (data: any) => void
  onOpen?: (event: Event) => void
  onError?: (event: Event) => void
  onClose?: (event: CloseEvent) => void
  onRealTime?: (data: any) => void  // 添加新的回调函数处理实时数据
}

// 心跳检测配置
interface HeartbeatConfig {
  enabled: boolean
  interval: number
  message: string
}

class WebSocketService {
  private ws: WebSocket | null = null
  private options: WebSocketOptions
  private reconnectAttempts = 0
  private maxReconnectAttempts = 5
  private reconnectTimeout: number | null = null

  // 心跳检测相关
  private heartbeatTimer: number | null = null
  private heartbeatConfig: HeartbeatConfig = {
    enabled: true,
    interval: 300000, // 5分钟
    message: 'ping'
  }

  constructor(options: WebSocketOptions) {
    this.options = options
  }

  // 连接WebSocket
  connect() {
    // 检查是否已经连接
    if (this.ws && this.ws.readyState === WebSocket.OPEN) {
      console.log('WebSocket已连接')
      return
    }

    try {
      //如果是测试环境，则使用测试环境地址，否则使用正式环境地址
      let wsUrl = ''
      if (import.meta.env.VITE_APP_ENV === 'development') {
        // wsUrl = `ws://127.0.0.1:5000/webSocket/${userStore.userInfo.userId}`;
        wsUrl = `ws://47.109.61.132:5000/webSocket/${userStore.userInfo.userId}`;
      } else {
        //处理协议、ip、端口
        const protocol = window.location.protocol === 'https:' ? 'wss' : 'ws';
        const ip = '47.109.61.132' //window.location.hostname;
        const port = '5000' //window.location.port;
        wsUrl = `${protocol}://${ip}:${port}/webSocket/${userStore.userInfo.userId}`;
      }

      // 创建WebSocket连接
      if ('WebSocket' in window) {
        this.ws = new WebSocket(wsUrl);
      } else if ('MozWebSocket' in (window as any)) {
        this.ws = new (window as any).MozWebSocket(wsUrl);
      } else {
        throw new Error('当前浏览器不支持WebSocket');
      }

      // 连接成功回调
      this.ws.onopen = (event) => {
        console.log('WebSocket连接成功', event);
        this.reconnectAttempts = 0;

        // 开始心跳检测
        this.startHeartbeat();

        if (this.options.onOpen) {
          this.options.onOpen(event);
        }
      }

      // 接收消息回调
      this.ws.onmessage = (event) => {

        // 重置心跳
        this.resetHeartbeat();

        if (this.options.onMessage) {
          //解析event.data
          const res = JSON.parse(event.data)
          if (res.code === '0') {
            this.options.onMessage(res.data)
          }
        }
      }

      // 错误处理回调
      this.ws.onerror = (event) => {
        console.error('WebSocket连接错误', event);
        if (this.options.onError) {
          this.options.onError(event);
        }
      }

      // 连接关闭回调
      this.ws.onclose = (event) => {
        console.log('WebSocket连接已关闭', event);

        // 停止心跳
        this.stopHeartbeat();

        if (this.options.onClose) {
          this.options.onClose(event);
        }

        this.attemptReconnect();
      }
    } catch (error) {
      console.error('初始化WebSocket时发生错误:', error);
    }
  }

  // 尝试重新连接
  private attemptReconnect() {
    if (this.reconnectAttempts >= this.maxReconnectAttempts) {
      console.log(`已达到最大重连次数(${this.maxReconnectAttempts})，停止重连`);
      return;
    }

    this.reconnectAttempts++;
    const reconnectDelay = 10000;
    console.log(`尝试在${reconnectDelay}ms后重新连接，尝试次数:${this.reconnectAttempts}/${this.maxReconnectAttempts}`);

    this.reconnectTimeout = window.setTimeout(() => {
      console.log(`正在尝试第${this.reconnectAttempts}/${this.maxReconnectAttempts}次重新连接...`);
      this.connect();
    }, reconnectDelay);
  }

  // 立即重连
  reconnect() {
    if (this.ws) {
      this.ws.close();
      this.ws = null;
    }
    this.connect();
  }

  // 发送消息
  sendMessage(data: string | object) {
    if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
      console.error('WebSocket未连接，无法发送消息');
      return false;
    }

    try {
      // 如果是对象，将其转换为JSON字符串
      const message = typeof data === 'object' ? JSON.stringify(data) : data;
      this.ws.send(message);
      return true;
    } catch (error) {
      console.error('发送消息错误:', error);
      return false;
    }
  }

  // 关闭连接
  disconnect() {
    this.stopHeartbeat();

    if (this.reconnectTimeout) {
      clearTimeout(this.reconnectTimeout);
      this.reconnectTimeout = null;
    }

    if (this.ws) {
      this.ws.close();
      this.ws = null;
    }
  }

  // 获取连接状态
  getStatus() {
    if (!this.ws) {
      return 'CLOSED';
    }
    switch (this.ws.readyState) {
      case WebSocket.CONNECTING:
        return 'CONNECTING';
      case WebSocket.OPEN:
        return 'OPEN';
      case WebSocket.CLOSING:
        return 'CLOSING';
      case WebSocket.CLOSED:
        return 'CLOSED';
      default:
        return 'UNKNOWN';
    }
  }

  // 心跳检测相关方法
  private startHeartbeat() {
    if (!this.heartbeatConfig.enabled) return;

    this.resetHeartbeat();
  }

  private resetHeartbeat() {
    this.stopHeartbeat();

    if (!this.heartbeatConfig.enabled) return;

    this.heartbeatTimer = window.setInterval(() => {
      if (this.ws && this.ws.readyState === WebSocket.OPEN) {
        console.log('发送心跳包保持连接');
        this.sendMessage(this.heartbeatConfig.message);
      } else {
        console.log('断开状态，尝试重连');
        this.reconnect();
      }
    }, this.heartbeatConfig.interval);
  }

  private stopHeartbeat() {
    if (this.heartbeatTimer) {
      clearInterval(this.heartbeatTimer);
      this.heartbeatTimer = null;
    }
  }

  // 配置心跳检测
  configHeartbeat(config: Partial<HeartbeatConfig>) {
    this.heartbeatConfig = { ...this.heartbeatConfig, ...config };

    // 如果已连接，重置心跳
    if (this.ws && this.ws.readyState === WebSocket.OPEN) {
      this.resetHeartbeat();
    }
  }

}

export default WebSocketService; 